Telegram Group & Telegram Channel
Почему std::move может не сработать, как ты ожидал

Всё просто? Хочешь передать объект по move — вызываешь std::move(obj) и думаешь, что теперь точно будет перемещение. Но не всё так однозначно.


void foo(std::string s) {
std::string local = std::move(s);
}


Выглядит, будто s перемещается в local. Но на практике — нет. Здесь копирование. Почему?

s — это lvalue, несмотря на std::move в правой части. А значит, выбирается std::string конструктор копирования, если только он не удалён.

Чтобы реально переместить, нужно явно вызвать std::move:


std::string local = std::move(s); // ОК — move-конструктор


Но будь осторожен:


std::string getStr() {
std::string tmp = "hello";
return std::move(tmp); // Не всегда нужно!
}


Здесь std::move ломает RVO (Return Value Optimization). Компилятор мог бы вернуть tmp без перемещения, вообще без копий. А std::move мешает, заставляя делать move-конструктор.

Выводы:
std::move не двигает, он обещает, что ты больше не тронешь объект
– Будь осторожен с std::move в return
– Не забудь, что lvalue остаётся lvalue, даже если ты его "обернул" std::move

➡️ @cpp_geek



tg-me.com/cpp_geek/316
Create:
Last Update:

Почему std::move может не сработать, как ты ожидал

Всё просто? Хочешь передать объект по move — вызываешь std::move(obj) и думаешь, что теперь точно будет перемещение. Но не всё так однозначно.


void foo(std::string s) {
std::string local = std::move(s);
}


Выглядит, будто s перемещается в local. Но на практике — нет. Здесь копирование. Почему?

s — это lvalue, несмотря на std::move в правой части. А значит, выбирается std::string конструктор копирования, если только он не удалён.

Чтобы реально переместить, нужно явно вызвать std::move:


std::string local = std::move(s); // ОК — move-конструктор


Но будь осторожен:


std::string getStr() {
std::string tmp = "hello";
return std::move(tmp); // Не всегда нужно!
}


Здесь std::move ломает RVO (Return Value Optimization). Компилятор мог бы вернуть tmp без перемещения, вообще без копий. А std::move мешает, заставляя делать move-конструктор.

Выводы:
std::move не двигает, он обещает, что ты больше не тронешь объект
– Будь осторожен с std::move в return
– Не забудь, что lvalue остаётся lvalue, даже если ты его "обернул" std::move

➡️ @cpp_geek

BY C++ geek




Share with your friend now:
tg-me.com/cpp_geek/316

View MORE
Open in Telegram


C geek Telegram | DID YOU KNOW?

Date: |

Telegram hopes to raise $1bn with a convertible bond private placement

The super secure UAE-based Telegram messenger service, developed by Russian-born software icon Pavel Durov, is looking to raise $1bn through a bond placement to a limited number of investors from Russia, Europe, Asia and the Middle East, the Kommersant daily reported citing unnamed sources on February 18, 2021.The issue reportedly comprises exchange bonds that could be converted into equity in the messaging service that is currently 100% owned by Durov and his brother Nikolai.Kommersant reports that the price of the conversion would be at a 10% discount to a potential IPO should it happen within five years.The minimum bond placement is said to be set at $50mn, but could be lowered to $10mn. Five-year bonds could carry an annual coupon of 7-8%.

Telegram Auto-Delete Messages in Any Chat

Some messages aren’t supposed to last forever. There are some Telegram groups and conversations where it’s best if messages are automatically deleted in a day or a week. Here’s how to auto-delete messages in any Telegram chat. You can enable the auto-delete feature on a per-chat basis. It works for both one-on-one conversations and group chats. Previously, you needed to use the Secret Chat feature to automatically delete messages after a set time. At the time of writing, you can choose to automatically delete messages after a day or a week. Telegram starts the timer once they are sent, not after they are read. This won’t affect the messages that were sent before enabling the feature.

C geek from us


Telegram C++ geek
FROM USA